package com.qf.watcher;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.nio.file.Watchable;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ZkWatcher implements Watcher {

    private  ZooKeeper zooKeeper;
    private static final String ZKADDR = "10.9.12.200:8601,10.9.12.200:8602,10.9.12.200:8603";
    private static CountDownLatch countDownLatch = new CountDownLatch(1);//用作阻塞的, 1 的意思是只需有一个地方执行了放行就放行所有阻塞的地方

    public ZkWatcher() throws IOException, KeeperException, InterruptedException {
        System.out.println("连接zk 服务器");
        zooKeeper=new ZooKeeper(ZKADDR, 50000, this);
//       开启监听

        zooKeeper.exists("/04cacheservice",true);
    }

    @Override
    public void process(WatchedEvent event) {
        Event.KeeperState state = event.getState();
        String path = event.getPath();
        Event.EventType type = event.getType();
//          连接成功   没有节点
        if(state==Event.KeeperState.SyncConnected&&type==Event.EventType.None){
            System.err.println("连接zk 服务器成功");
            System.out.println("收到的节点是"+path+" 创建成功的事件");
//            连接成功  有节点了
        }else if(state == Event.KeeperState.SyncConnected && type == Event.EventType.NodeCreated){
            System.out.println("收到的节点是"+path+" 创建成功的事件");
            try {
//                获取子节点  开启监听
                zooKeeper.getChildren("/03cacheservice",true);
//                获取数据  开启监听
                zooKeeper.getData("/03cacheservice",true,null);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            连接成功   节点数据发生变化了
        }else if(state == Event.KeeperState.SyncConnected && type == Event.EventType.NodeDataChanged){
            byte[] data = new byte[0];
            try {
                data = zooKeeper.getData(path, true, null);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.err.println("收到节点:" + path + "数据变化的事件"+new String(data));
//            连接成功  并且子节点发生的改变
        }else if(state == Event.KeeperState.SyncConnected && type == Event.EventType.NodeChildrenChanged){
            List<String> stringList = null;
            try {
                stringList = zooKeeper.getChildren(path, true);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.err.println("收到节点:" + path + "子节点变化的事件"+stringList);
        }

    }
}
